package com.caszx.chargingpile.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.app.base.app.BaseTopBarDelayActivity;
import com.app.base.app.BaseTopBarNetActivity;
import com.app.utils.DiskUser;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.socks.library.KLog;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import me.itangqi.waveloadingview.WaveLoadingView;
import okhttp3.Call;

/**
 * 充电
 */
public class BatteryChargeActivity extends BaseTopBarNetActivity implements View.OnClickListener {

    private String ordersId;
    private TextView txt_time;
    private WaveLoadingView waveLoadingView;
    private TextView btn_stop_charge;

    @Override
    protected void init() {
        ordersId = getIntent().getStringExtra("ID");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setCenterTitle(R.string.battery_sharge);
    }

    public void onEvent(String action) {
        if (EventBusAction.ACTION_USER_PAY_SUCCESS.equals(action)) {
            //付款成功
            finish();
        }
    }

    @Override
    protected void onLoad() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        params.put("ordersId", ordersId);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_DETAIL_CHARGE)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        showErrorView(R.string.error_network);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code == -100) {
                                DialogHelp.showDialogOnlyMesg(BatteryChargeActivity.this, getResources().getString(R.string.error_minus_100), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(BatteryChargeActivity.this, UserSignInActivity.class);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                showErrorView(getResources().getString(R.string.error_minus_100));
                                return;
                            }
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                showErrorView(resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    showContentView();
                                    steupContentView(response);
                                } catch (JSONException e) {
                                    showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });

    }

    @Override
    protected View initOnloadedView() {
        View view = getLayoutInflater().inflate(R.layout.activity_battery_charge, null);
        findView(view);
        return view;
    }

    protected void findView(View view) {
        btn_stop_charge = (TextView) view.findViewById(R.id.btn_stop_charge);
        btn_stop_charge.setOnClickListener(this);
        view.findViewById(R.id.btn_error_post).setOnClickListener(this);
        txt_time = (TextView) view.findViewById(R.id.txt_time);
        waveLoadingView = (WaveLoadingView) view.findViewById(R.id.waveLoadingView);
    }

    private void steupContentView(JSONObject jsonObject) {
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("充电时长 HH 时 mm 分");
        long timeLong = jsonObject.optLong("timeLong");
//        txt_time.setText(simpleDateFormat.format(new Date(timeLong*1000)));
        int h = 0, m = 0, s = 0;

        if (timeLong > 3600) {
            h = (int) (timeLong / 3600);
            m = (int) (timeLong % 3600) / 60;
            s = (int) (timeLong - h * 3600 - m * 60);
        } else {
            m = (int) (timeLong % 3600) / 60;
            s = (int) (timeLong - m * 60);
        }
        txt_time.setText("充电时长 " + h + "时" + m + "分" + s + "秒");
        StringBuilder builderTop = new StringBuilder();
//        builderTop.append("充电电量:").append(jsonObject.optString("chargeQuantity")).append("%\n");
        builderTop.append("电压:").append(jsonObject.optString("voltage")).append("V\n");
        builderTop.append("电流:").append(jsonObject.optString("current")).append("A\n");
        waveLoadingView.setTopTitle(builderTop.toString());
        waveLoadingView.setTopTitleSize(13);
        waveLoadingView.setTopTitleColor(Color.WHITE);


        waveLoadingView.setCenterTitle("现在电量:" + jsonObject.optString("soce") + "%");
        waveLoadingView.setCenterTitleColor(Color.WHITE);

        waveLoadingView.setBottomTitle("充电电量:" + jsonObject.optString("chargeQuantity") + "Kwh");
        waveLoadingView.setBottomTitleColor(Color.WHITE);

        handler.sendEmptyMessageDelayed(0, 30 * 1000);

        //0:app,1:刷卡
        if (jsonObject.optInt("chargeType") == 0) {
            btn_stop_charge.setVisibility(View.VISIBLE);
        } else {
            btn_stop_charge.setVisibility(View.INVISIBLE);
        }


    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            OkHttpUtils.post()
                    .url(ConstantUrl.URL_DETAIL_CHARGE)
                    .addParams("token", DiskUser.getStringValueByKey(BatteryChargeActivity.this, "token"))
                    .addParams("ordersId", ordersId)
                    .tag(BatteryChargeActivity.this)
                    .build()
                    .execute(new JsonCallback() {
                        @Override
                        public void onError(Call call, Exception e) {
                        }

                        @Override
                        public void onResponse(JSONObject response) {
                            JSONObject resultJsonObject = response.optJSONObject("result");
                            if (resultJsonObject != null) {
                                int code = resultJsonObject.optInt("code");
                                if (code < 0) {
                                } else {
                                    try {
                                        steupContentView(response);
                                    } catch (JSONException e) {
                                        showErrorView(R.string.error_parser_json);
                                    }
                                }
                            }
                        }
                    });


            handler.sendEmptyMessageDelayed(0, 30 * 1000);

        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_stop_charge:
                Dialog.Builder builder = null;
                builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
                    @Override
                    public void onPositiveActionClicked(DialogFragment fragment) {
                        super.onPositiveActionClicked(fragment);
                        getChargePrice();

                    }

                    @Override
                    public void onNegativeActionClicked(DialogFragment fragment) {
                        super.onNegativeActionClicked(fragment);
                    }
                };

                ((SimpleDialog.Builder) builder)
                        .message("确认后开始支付")
                        .title("是否停止充电?")
                        .positiveAction("确定")
                        .negativeAction("取消");
                DialogFragment fragment = DialogFragment.newInstance(builder);
                fragment.show(getSupportFragmentManager(), null);

                break;

            case R.id.btn_error_post:
                Intent intent = new Intent(this, ErrorActivity.class);
                intent.putExtra("ID", ordersId);
                startActivity(intent);
                break;
        }
    }


    /**
     * 得到充电的费用
     */
    private void getChargePrice() {
        showProgressDialog("提交中");
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        params.put("ordersId", ordersId);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_STOP_CHARGE)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        // showErrorView(R.string.error_network);
                        SnackbarHelp.showSnackbarMsg(BatteryChargeActivity.this, getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code == -100) {
                                DialogHelp.showDialogOnlyMesg(BatteryChargeActivity.this, getResources().getString(R.string.error_minus_100), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(BatteryChargeActivity.this, UserSignInActivity.class);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                return;
                            }
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                //showErrorView(resultJsonObject.optString("msg"));
                                SnackbarHelp.showSnackbarMsg(BatteryChargeActivity.this, resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    Intent intent = new Intent(BatteryChargeActivity.this, PayActivity.class);
                                    //充电的订单号
                                    intent.putExtra("ordersId", response.optString("ordersId"));
                                    //电站名称
                                    intent.putExtra("stationName", response.optString("stationName"));
                                    //时长
                                    intent.putExtra("timeLong", response.optLong("timeLong"));
                                    //时间段
                                    intent.putExtra("timeSlot", response.optLong("timeSlot"));
                                    //用电量
                                    intent.putExtra("changePower", response.optDouble("changePower"));
                                    //充电费用
                                    intent.putExtra("chargeFees", response.optDouble("chargeFees"));
                                    //服务费
                                    intent.putExtra("serverFees", response.optDouble("serverFees"));
                                    //停车费
                                    intent.putExtra("stopFees", response.optDouble("stopFees"));
                                    //总费用
                                    intent.putExtra("totalFees", response.optDouble("totalFees"));
                                    startActivity(intent);
                                    finish();
                                    EventBus.getDefault().post(EventBusAction.ACTION_USER_PAY_SUCCESS);
                                } catch (JSONException e) {
                                    SnackbarHelp.showSnackbarMsg(BatteryChargeActivity.this, getString(R.string.error_parser_json));
                                    //showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        handler.removeMessages(0);
        handler.removeCallbacks(null);
        super.onDestroy();
    }
}
